package com.itlong.cloud.network.tcp.socket;

import org.slf4j.Logger;import org.slf4j.LoggerFactory;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;

/**
 * <desc>
 * 下发TCP指令到设备。
 * </desc>
 *
 * @createDate 2018/9/11
 */
public class ScocketClient {
    private static final Logger LOG = LoggerFactory.getLogger(ScocketClient.class);

    public static byte[] sendSocket(String ip, String port, byte[] message) {
        String ret = "";
        DataInputStream input = null;
        DataOutputStream out = null;
        try {
            //向服务器端发送请求，服务器IP地址和服务器监听的端口号
            Socket client = new Socket(ip, Integer.parseInt(port));
            client.setSoTimeout(5000);//设置超时时间

            //读取服务器端数据
            input = new DataInputStream(client.getInputStream());
            //向服务器端发送数据
            out = new DataOutputStream(client.getOutputStream());
            out.write(message);
            out.flush();
            byte[] buffer = new byte[1024];
            if (input == null) {
                return null;
            }
            int size = input.read(buffer);
            if (size > 0) {
                byte[] bytes = new byte[size];
                System.arraycopy(buffer, 0, bytes, 0, size);
                return bytes;
            }

        } catch (Exception e) {
            LOG.error("socket发送异常:" + e);
        } finally {
            try {
                out.close();
                input.close();
            } catch (Exception e) {
                LOG.error("流关闭异常:" + e);
            }
        }
        return null;
    }
}
